import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: 'login' */'@/views/login/index')
  },
  {
    path: '/',
    name: 'course',
    component: () => import(/* webpackChunkName: 'course' */'@/views/course/index'),
    meta: {
      footShow: true
    }
  },
  {
    path: '/course-info/:id',
    name: 'course-info',
    component: () => import(/* webpackChunkName: 'course-info' */'@/views/course-info/index'),
    props: true
  },
  {
    path: '/learn',
    name: 'learn',
    component: () => import(/* webpackChunkName: 'learn' */'@/views/learn/index'),
    meta: {
      footShow: true,
      requiresAuth: true
    }
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import(/* webpackChunkName: 'mine' */'@/views/mine/index'),
    meta: {
      footShow: true,
      requiresAuth: true
    }
  },
  {
    path: '/pay/:id',
    name: 'pay',
    component: () => import(/* webpackChunkName: 'pay' */'@/views/pay/index'),
    props: true,
    meta: { requiresAuth: true }
  },
  {
    path: '/courseVideo/:id',
    name: 'courseVideo',
    component: () => import(/* webpackChunkName: 'courseVideo' */'@/views/course-info/courseVideo'),
    props: true
  },
  {
    path: '*',
    name: 'error-page',
    component: () => import(/* webpackChunkName: 'error-page' */'@/views/error-page/index')
  }
]

const router = new VueRouter({
  routes
})

// 路由导航守卫,只有满足了条件的才能够被访问
router.beforeEach((to, from, next) => {
  // 验证to路由是否需要身份验证
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 需要验证
    // 判断store 里面的 state里的user 是否存在
    if (!store.state.user) {
      // 不存在,就调回登录页面
      next({
        path: '/login',
        // 并携带查询参数, 当登录成功以后重定向到to路由的地址
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else {
    // 不需要验证,直接通过
    next()
  }
})
export default router
